use clap::Parser;
use core::result::Result;
use log::LevelFilter;
use rust_mq_server::{Error, Server};
use std::str::FromStr;
use std::{env, net::IpAddr};

#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Cli {
    #[arg(short, long, default_value_t = String::from("0.0.0.0"))]
    ip: String,

    #[arg(short, long, default_value_t = 6666)]
    port: u16,
}

#[tokio::main]
async fn main() -> Result<(), Error> {
    init_log();

    let cli = Cli::parse();
    let ip_addr = match cli.ip.parse::<IpAddr>() {
        Ok(ip) => ip,
        Err(_e) => "0.0.0.0".parse().unwrap(),
    };

    let mut server = Server::new();
    server.start(ip_addr, cli.port).await?;

    Ok(())
}

fn init_log() {
    let log_level = match env::var("RUST_LOG") {
        Ok(val) => val,
        Err(_) => "info".to_string(),
    };

    let level_filter = match LevelFilter::from_str(&log_level) {
        Ok(filter) => filter,
        Err(_) => LevelFilter::Info, // Default to Info if parsing fails
    };

    // Configure logger
    env_logger::builder().filter_level(level_filter).init();
}
